<?php

namespace app\api\controller;
use app\api\model\Rule as RuleModel;
use app\Request;

class Rule
{
    public function index(Request $request)
    {
        $limit = $request->param('limti') ? $request->param('limit') : 10;
        $page = $request->param('page') ? $request->param('page') : 1;
        $db = new RuleModel();
        $list = $db->where('status',1)->limit($limit)->page($page)->select();
        if (!$list->isEmpty()) {//半段数据是否为空
            $count = $db->where('status',1)->count();
            return json(['code' => 200, 'msg' => '成功', 'data' => $list, 'total' => $count]);
        } else {
            return json(['code' => 500, 'msg' => '暂无数据']);
        }
    }


    public function delete(Request $request)
    {
        $id = $request->param('id');
        $db = new RuleModel();
        return json($db->del($id));
    }



    public function add(Request $request)
    {
        if (!$request->isPost()) {
            return json(['code' => 500, 'msg' => '请求方式错误']);
        }
        $data = $request->param();
        $db = new RuleModel();

        $res = $db->save($data);

        if ($res) {
            return json(['code' => 200, 'msg' => '操作成功']);
        } else {
            return json(['code' => 500, 'msg' => '操作失败']);
        }
    }

    public function update(Request $request)
    {
        if (!$request->isPost()) {
            return json(['code' => 500, 'msg' => '请求方式错误']);
        }
        $data = $request->param();
        $db = new RuleModel();
        $info = $db->where('id', $data['id'])->find();
        if (empty($info)) {
            return json(['code' => 500, 'msg' => '数据不存在']);
        }
        $res = $db->update($data, ['id' => $data['id']]);

        if ($res) {
            return json(['code' => 200, 'msg' => '操作成功']);
        }else {
            return json(['code' => 500, 'msg' => '操作失败']);
        }

    }


}